package org.ali.structuralpattern.proxypattern.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLIB动态代理，支持无接口
 */
public class ShapeProxy3 implements MethodInterceptor {
    private final Object object;
    private final String name;

    public ShapeProxy3(Object object, String name) {
        this.object = object;
        this.name = name;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("CGLIB动态代理，访问者：" + name);
        return method.invoke(object, objects);
    }

    /**
     * 获取代理实例
     */
    public Object getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);
        enhancer.setSuperclass(object.getClass());
        return enhancer.create();
    }
}
